#include "scroll.h"
#include <QTimer>

Scroll::Scroll(QWidget *parent) : QScrollArea(parent)
{
	caretX = 0;
	caretY = 0;
	setMouseTracking(true);
	toscroll = 0;
	zoneR = new QRect();
	zoneL = new QRect();
	QTimer *timer = new QTimer(this);
	connect(timer, SIGNAL(timeout()), this, SLOT(scrolling()));
	timer->start(50);
	timerPlay = new QTimer(this);
	connect(timerPlay, SIGNAL(timeout()), this, SLOT(scrollingPlay()));
	 
}

void Scroll::setWidget(QWidget *wid)
{
	QScrollArea::setWidget(wid);
	connect(this, SIGNAL(notScroll(bool)), wid, SLOT(scrolling(bool)));
	connect(this, SIGNAL(caretMove(int)), wid, SLOT(caretMoving(int)));
}

void Scroll::resizeEvent(QResizeEvent* /* event */)
{
	QWidget *wid = widget();

	if (wid != 0) {
		wid->resize(width(), height());
	}

	int zoneLength = 25;
	zoneR->setRect(width() - zoneLength, 0, zoneLength, height());
        zoneL->setRect(0, 0, zoneLength, height());

}

void Scroll::play(bool started)
{
	if (started) {
		caretX = 0;
		timerPlay->start(120);	
	}
	else {
		timerPlay->stop();
		emit caretMove(-1);
	}
}

void Scroll::scrollingPlay()
{
	int step = 5;
	caretX += step;
	if (caretX < widget()->width()) {
		emit caretMove(caretX);
		ensureVisible(caretX, caretY, 200);
	}
	else {
		play(false);
	}
}

void Scroll::scrolling()
{
	int scrollValue = 10;
	QScrollBar *hb = horizontalScrollBar();
	hb->setValue(hb->value() + scrollValue * toscroll);
}

void Scroll::wheelEvent(QWheelEvent *e)
{
	QScrollBar *hb = horizontalScrollBar();
	hb->setValue(hb->value() - e->delta());
	emit notScroll(false);
}

void Scroll::setToScroll(int newToScroll)
{
	toscroll = newToScroll;
	if (toscroll != 0)
		emit notScroll(false);
	else
		emit notScroll(true);
}

void Scroll::leaveEvent ( QEvent * /* event */)
{
	setToScroll(0);
}

void Scroll::mouseMoveEvent(QMouseEvent *e)
{
	QScrollBar *hb = horizontalScrollBar();
	if (zoneR->contains(e->pos()) && hb->value() < hb->maximum()) {
		setToScroll(1);
	}
	else if (zoneL->contains(e->pos()) && hb->value() > hb->minimum()) {
		setToScroll(-1);
	}
	else 
		setToScroll(0);
	
	e->ignore();
}
